/*
{*******************************************************************}
{                                                                   }
{       KS-GANTT DotNet Library                                     }
{       Gantt-Charting Control for Windows Forms                    }
{                                                                   }
{       Copyright (c) 2009 - 2012 by Kroll-Software                 }
{       All Rights Reserved                                         }
{                                                                   }
{   This code is provided 'as is',                                  }
{   without warranties of any kind. Use at your own risk.           }                                                              
{                                                                   }
{   As a license holder of the KS-Gantt Control,                    }
{   you may freely redistribute executables based on                }
{   and created with these contents.                                }
{   You can modify the source code to meet your needs.              }
{                                                                   }
{   However, you must not publish, redistribute or transfer         }
{   this source code to 3rd parties under any conditions.           }
{                                                                   } 
{*******************************************************************}
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using KS.Common;

namespace MiGuava.SqlServer
{
    public partial class ucSqlServerConnect : UserControl
    {
        public enum ConnectionModes
        {
            Connect,
            CreateDatabase
        }

        private ConnectionModes m_ConnectionMode = ConnectionModes.Connect;
        public ConnectionModes ConnectionMode
        {
            get
            {
                return m_ConnectionMode;
            }
            set
            {
                m_ConnectionMode = value;

                switch (m_ConnectionMode)
                {
                    case ConnectionModes.Connect:
                        lblDatabase.Text = Properties.Resources.SQLConnectExistingDatabaseCaption;
                        break;

                    case ConnectionModes.CreateDatabase:
                        lblDatabase.Text = Properties.Resources.SQLConnectNewDatabaseCaption;
                        break;
                }
            }
        }


        public ucSqlServerConnect()
        {
            InitializeComponent();

            radAuthWin.CheckedChanged += new EventHandler(radAuthWin_CheckedChanged);
            radAuthSQL.CheckedChanged += new EventHandler(radAuthSQL_CheckedChanged);

            cboServer.DropDown += new EventHandler(cboServer_DropDown);
            cboDatabase.DropDown += new EventHandler(cboDatabase_DropDown);
        }

        public void InitLoad()
        {
            EnableControls();

            try
            {                
                if (!cboServer.Enabled && txtPassword.Enabled)
                    txtPassword.Focus();

                if (radAuthSQL.Checked && cboServer.Text != "")
                    txtPassword.Focus();

                if (ConnectionMode == ConnectionModes.CreateDatabase)
                {
                    if (cboServer.Text != "" && !(radAuthSQL.Checked && txtPassword.Text == ""))
                        cboDatabase.Focus();
                }

            }
            catch { }
        }
        
        public string UserName
        {
            get
            {
                return txtUser.Text.Trim();
            }
            set
            {
                txtUser.Text = value;
            }
        }


        public string Password
        {
            get
            {
                return txtPassword.Text;
            }
            set
            {
                txtPassword.Text = value;
            }
        }

        public string Server
        {
            get
            {
                return cboServer.Text.Trim();
            }
            set
            {                
                cboServer.Text = value;
            }
        }

        public string Database
        {
            get
            {
                return cboDatabase.Text.Trim();
            }
            set
            {
                cboDatabase.SelectedIndex = -1;
                cboDatabase.Text = value;
            }
        }

        public SQLAuthTypes SQLAuth
        {
            get
            {
                if (radAuthWin.Checked)
                    return SQLAuthTypes.SQLAuth_Win;
                else
                    return SQLAuthTypes.SQLAuth_SQL;
            }
            set
            {
                switch (value)
                {
                    case SQLAuthTypes.SQLAuth_Win:
                        radAuthWin.Checked = true;
                        break;

                    default:
                        radAuthSQL.Checked = true;
                        break;
                }
            }
        }

        public string ConnectionString
        {
            get
            {
                return KS.Common.DatabaseHelpers.GetSQLServerConnectionString(cboServer.Text, cboDatabase.Text, radAuthWin.Checked, txtUser.Text, txtPassword.Text, 20);
            }
        }

        private void LoadServers()
        {
            if (cboServer.Items.Count > 0)
                return;

            cboServer.Items.Clear();

            Cursor.Current = Cursors.WaitCursor;

            DataTable tblServers;
            string strServer;
            string strInstance;
            string strFullName;

            try
            {
                tblServers = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();

                foreach (DataRow r in tblServers.Rows)
                {
                    strServer = Strings.GetSafeString(r["ServerName"]);
                    strInstance = Strings.GetSafeString(r["InstanceName"]);

                    strFullName = strServer;
                    if (strInstance != "")
                        strFullName += "\\" + strInstance;

                    if (!cboServer.Items.Contains(strFullName))
                        cboServer.Items.Add(strFullName);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                Program.ErrMsgBox(ex.Message);
                return;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        void radAuthWin_CheckedChanged(object sender, EventArgs e)
        {
            EnableControls();
        }

        void radAuthSQL_CheckedChanged(object sender, EventArgs e)
        {
            EnableControls();
        }

        public void EnableControls()
        {
            lblUser.Enabled = radAuthSQL.Checked;
            lblPassword.Enabled = radAuthSQL.Checked;
            txtUser.Enabled = radAuthSQL.Checked;
            txtPassword.Enabled = radAuthSQL.Checked;
        }


        public bool IsValid(bool CheckDatabase, bool ShowMessages)
        {
            if (cboServer.Text == "")
            {
                if (ShowMessages)
                {
                    Program.ErrMsgBox(Properties.Resources.SQLLogOn1);
                    cboServer.Focus();
                }
                return false;
            }

            if (radAuthSQL.Checked)
            {
                if (txtUser.Text == "")
                {
                    if (ShowMessages)
                    {
                        Program.ErrMsgBox(Properties.Resources.SQLLogOn2);
                        txtUser.Focus();
                    }
                    return false;
                }
            }

            if (CheckDatabase)
            {
                if (cboDatabase.Text == "")
                {
                    if (ShowMessages)
                    {
                        Program.ErrMsgBox(Properties.Resources.SQLLogOn3);
                        cboDatabase.Focus();                        
                    }
                    return false;
                }
                else if (ConnectionMode == ConnectionModes.CreateDatabase)
                {
                    if (cboDatabase.Items.Contains(cboDatabase.Text))
                    {
                        if (ShowMessages)
                        {
                            Program.ErrMsgBox(Properties.Resources.SQLConnectDatabaseExists);
                            cboDatabase.Focus();
                        }

                        return false;
                    }
                }
            }

            return true;
        }

        public void TestConnection()
        {
            if (!IsValid(true, true))
            {
                return;
            }

            System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection();

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                Conn.ConnectionString = KS.Common.DatabaseHelpers.GetSQLServerConnectionString(cboServer.Text, cboDatabase.Text, radAuthWin.Checked, txtUser.Text, txtPassword.Text, 20);
                Conn.Open();

            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                Program.ErrMsgBox(ex.Message);
                return;
            }

            Cursor.Current = Cursors.Default;
            Program.InfoMsgBox(Properties.Resources.SQLLogOn4);
        }

        void cboServer_DropDown(object sender, EventArgs e)
        {
            LoadServers();
        }

        void cboDatabase_DropDown(object sender, EventArgs e)
        {
            if (!IsValid(false, true))
            {
                cboDatabase.DroppedDown = false;
                return;
            }

            Cursor.Current = Cursors.WaitCursor;

            cboDatabase.Items.Clear();

            try
            {
                System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection();

                System.Data.SqlClient.SqlConnectionStringBuilder connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
                connectionStringBuilder.DataSource = cboServer.Text;
                connectionStringBuilder.IntegratedSecurity = radAuthWin.Checked;
                connectionStringBuilder.UserID = txtUser.Text;
                connectionStringBuilder.Password = txtPassword.Text;
                connectionStringBuilder.ConnectTimeout = 20;

                Conn.ConnectionString = connectionStringBuilder.ConnectionString;
                Conn.Open();

                DataTable tblCatalogs = Conn.GetSchema("databases");

                string strCatalog;
                foreach (DataRow dr in tblCatalogs.Rows)
                {
                    strCatalog = Strings.GetSafeString(dr["database_name"]);
                    if (strCatalog != "" && strCatalog != "master" && strCatalog != "model" && strCatalog != "tempdb" && strCatalog != "msdb")
                    {
                        if (!cboDatabase.Items.Contains(strCatalog))
                            cboDatabase.Items.Add(strCatalog);
                    }
                }

                Cursor.Current = Cursors.Default;

            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                Program.ErrMsgBox(ex.Message);
            }

            if (cboDatabase.Items.Count > 0)
            {
                if (cboDatabase.Text == "")
                    cboDatabase.SelectedIndex = 0;
            }
            else
            {
                cboDatabase.Text = "";
                cboDatabase.DroppedDown = false;
            }
        }
    }
}
